package com.sqx.modules.pay.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.entity.ServiceTime;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.ServiceTimeService;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.bidding.entity.HelpBidding;
import com.sqx.modules.bidding.service.HelpBiddingService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.fixedClassify.service.FixedClassifyService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.orders.dao.OrdersDao;
import com.sqx.modules.orders.dao.PayOrderDao;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.orders.entity.PayOrder;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.pay.config.WXConfig;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.WxService;
import com.sqx.modules.taking.entity.OrderTaking;
import com.sqx.modules.taking.service.OrderTakingService;
import com.sqx.modules.task.dao.HelpOrderDao;
import com.sqx.modules.task.entity.HelpOrder;
import com.sqx.modules.task.entity.HelpTake;
import com.sqx.modules.task.service.HelpOrderService;
import com.sqx.modules.task.service.HelpTakeService;
import com.sqx.modules.utils.*;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @author fang
 * @date 2020/2/26
 */
@Service
@Slf4j
public class WxServiceImpl implements WxService {
    private static final String SPBILL_CREATE_IP = "127.0.0.1";
    private static final String TRADE_TYPE_APP = "APP";
    private static final String TRADE_TYPE_NATIVE = "NATIVE";
    private static final String TRADE_TYPE_JSAPI = "JSAPI";
    private static final String Wap = "MWEB";

    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private PayDetailsDao payDetailsDao;
    @Autowired
    private HelpBiddingService biddingService;
    @Autowired
    private PayOrderDao payOrderDao;
    @Autowired
    private HelpOrderService helpOrderService;
    @Autowired
    private UserMoneyDao userMoneyDao;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private MessageService messageService;
    @Autowired
    private OrderTakingService orderTakingService;
    @Autowired
    private HelpOrderDao helpOrderDao;
    @Autowired
    private ServiceTimeService serviceTimeService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private HelpTakeService helpTakeService;

    @Resource
    private UserDao userDao;

    @Resource
    private FixedClassifyService fixedClassifyService;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Override
    public Result payOrder(Long id, Integer classify, HttpServletRequest request) throws Exception {
        PayOrder bean = payOrderDao.selectById(id);
        if (bean == null) {
            return Result.error("订单生成失败，请重新下单！");
        }
        PayDetails payDetails = payDetailsDao.selectByOrderId(bean.getOrdersNo());
        if (payDetails == null) {
            payDetails = new PayDetails();
            payDetails.setState(0);
            payDetails.setCreateTime(sdf.format(new Date()));
            payDetails.setOrderId(bean.getOrdersNo());
            payDetails.setUserId(bean.getUserId());
            payDetails.setMoney(bean.getPayMoney().doubleValue());
            payDetails.setClassify(classify);
            payDetails.setType(1);
            payDetailsDao.insert(payDetails);
        }
        return pay(bean.getPayMoney().doubleValue(), classify, bean.getUserId(), bean.getOrdersNo(), null,request);
    }

    @Override
    public Result wxPayMember(Long ordersId, Integer classify, HttpServletRequest request) throws Exception {
        Orders orders = ordersDao.selectOne(new QueryWrapper<Orders>().eq("orders_id", ordersId));
        if (orders == null) {
            return Result.error("订单生成失败，请重新下单！");
        }
        PayDetails payDetails = payDetailsDao.selectByOrderId(orders.getOrdersNo());
        if (payDetails == null) {
            payDetails = new PayDetails();
            payDetails.setState(0);
            payDetails.setCreateTime(sdf.format(new Date()));
            payDetails.setOrderId(orders.getOrdersNo());
            payDetails.setUserId(orders.getUserId());
            payDetails.setMoney(orders.getPayMoney().doubleValue());
            payDetails.setClassify(classify);
            payDetails.setType(6);
            payDetailsDao.insert(payDetails);
        }
        return pay(orders.getPayMoney().doubleValue(), classify, orders.getUserId(), orders.getOrdersNo(), null,request);
    }



    @Override
    public Result wxPayOrder(Long id, Integer classify, HttpServletRequest request) throws Exception {
        Orders bean = ordersDao.selectById(id);
        if (bean == null) {
            return Result.error("订单生成失败，请重新下单！");
        }
        OrderTaking orderTaking = orderTakingService.getById(bean.getOrderTakingId());
        Integer counts = ordersDao.selectCount(new QueryWrapper<Orders>().in("state", 1, 2, 4).eq("order_taking_user_id", orderTaking.getUserId()).eq("order_taking_id", orderTaking.getId()).eq("start_time", bean.getStartTime()));
        ServiceTime serviceTime = serviceTimeService.getById(bean.getServiceTimeId());
        if (serviceTime.getNum() <= counts) {
            return Result.error("当前时段预约已满，请您更换其他时间段！");
        }

        PayDetails payDetails = payDetailsDao.selectByOrderId(bean.getOrdersNo());
        if (payDetails == null) {
            payDetails = new PayDetails();
            payDetails.setState(0);
            payDetails.setCreateTime(sdf.format(new Date()));
            payDetails.setOrderId(bean.getOrdersNo());
            payDetails.setUserId(bean.getUserId());
            payDetails.setMoney(bean.getPayMoney().doubleValue());
            payDetails.setClassify(classify);
            payDetails.setType(2);
            payDetailsDao.insert(payDetails);
        }



        return pay(bean.getPayMoney().doubleValue(), classify, bean.getUserId(), bean.getOrdersNo(), null,request);
    }


    @Override
    public Result wxPayHelpOrder(Long relationId,HelpOrder helpOrder, Integer classify, HttpServletRequest request) throws Exception {
        if (helpOrder.getCommission().doubleValue() <= 0) {
            return Result.error("金额必须大于0");
        }
        BigDecimal money=helpOrder.getMoney();
        if(relationId!=null){
            money=helpOrder.getCommission();
        }
        helpOrder.setOrderNo(getGeneralOrder());
        PayDetails payDetails = payDetailsDao.selectByOrderId(helpOrder.getOrderNo());
        if (payDetails == null) {
            payDetails = new PayDetails();
            payDetails.setState(0);
            payDetails.setCreateTime(sdf.format(new Date()));
            payDetails.setOrderId(helpOrder.getOrderNo());
            payDetails.setUserId(helpOrder.getUserId());
            payDetails.setMoney(money.doubleValue());
            payDetails.setClassify(classify);
            payDetails.setType(3);
            payDetails.setRemark(JSON.toJSONString(helpOrder));
            if (helpOrder.getRelationId() != null) {
                payDetails.setRelationId(helpOrder.getRelationId());
            }
            payDetailsDao.insert(payDetails);
        }
        helpOrderDao.updateById(helpOrder);

        return pay(money.doubleValue(), classify, helpOrder.getUserId(), helpOrder.getOrderNo(), null,request);
    }


    /**
     * 微信支付订单生成
     *
     * @param moneys     支付金额 带小数点
     * @param classify   类型 1app  2 二维码支付  3小程序 公众号支付
     * @param userId     用户id
     * @param outTradeNo 单号
     * @return
     * @throws Exception
     */
    private Result pay(Double moneys, Integer classify, Long userId, String outTradeNo, Integer type, HttpServletRequest request) throws Exception {
        //h5服务域名配置
        CommonInfo oneu = commonInfoService.findOne(19);
        String url;
        if (classify == 3) {
            url = oneu.getValue() + "/sqx_fast/app/wxPay/notifyJsApi";
        } else if (classify == 2 || classify ==4) {
            url = oneu.getValue() + "/sqx_fast/app/wxPay/notifyMp";
        } else {
            url = oneu.getValue() + "/sqx_fast/app/wxPay/notify";
        }
        String currentTimeMillis = (System.currentTimeMillis() / 1000) + "";
        //后台服务名称
        CommonInfo one = commonInfoService.findOne(12);
        log.info("回调地址：" + url);
        Double mul = AmountCalUtils.mul(moneys, 100);
        String money = String.valueOf(mul.intValue());
        String generateNonceStr = WXPayUtil.generateNonceStr();
        WXConfig config = new WXConfig();
        //微信小程序APPID        微信公众号APPID
        if (classify == 1) {
            config.setAppId(commonInfoService.findOne(74).getValue());
        } else if (classify == 2 || classify ==4) {
            config.setAppId(commonInfoService.findOne(5).getValue());
        } else {
            if (type != null && type == 2) {
                config.setAppId(commonInfoService.findOne(239).getValue());
            } else if (type != null && type == 3) {
                config.setAppId(commonInfoService.findOne(303).getValue());
            } else {
                config.setAppId(commonInfoService.findOne(45).getValue());
            }

        }
        //微信商户key
        config.setKey(commonInfoService.findOne(75).getValue());
        //微信商户号mchId
        config.setMchId(commonInfoService.findOne(76).getValue());
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<>();
        data.put("appid", config.getAppID());
        data.put("mch_id", config.getMchID());
        data.put("nonce_str", generateNonceStr);
        String body = one.getValue();
        data.put("body", body);
        //生成商户订单号，不可重复
        data.put("out_trade_no", outTradeNo);
        data.put("total_fee", money);
        //自己的服务器IP地址
        data.put("spbill_create_ip", SPBILL_CREATE_IP);
        //异步通知地址（请注意必须是外网）
        data.put("notify_url", url);
        //交易类型
        if(classify==1){
            data.put("trade_type", TRADE_TYPE_APP);
        }else if(classify==2){
            data.put("trade_type",TRADE_TYPE_JSAPI);
        }else if(classify==3){
            data.put("trade_type",TRADE_TYPE_JSAPI);
        }else if(classify==4){
            data.put("trade_type",Wap);
            data.put("spbill_create_ip", HttpClientUtil.getIpAddress(request));
        }else{
            data.put("trade_type",TRADE_TYPE_NATIVE);
        }
        //附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
        data.put("attach", "");
        data.put("sign", WXPayUtil.generateSignature(data, config.getKey(),
                WXPayConstants.SignType.MD5));
        if (classify == 3 || classify == 2) {
            UserEntity userEntity = userService.getById(userId);
            if (classify == 3) {
                if (type != null && type == 2) {
                    if (StringUtils.isNotBlank(userEntity.getShopOpenId())) {
                        data.put("openid", userEntity.getShopOpenId());
                    }
                } else if (type != null && type == 3) {
                    if (StringUtils.isNotBlank(userEntity.getMasterOpenId())) {
                        data.put("openid", userEntity.getMasterOpenId());
                    }
                } else {
                    if (StringUtils.isNotBlank(userEntity.getOpenId())) {
                        data.put("openid", userEntity.getOpenId());
                    }
                }

            } else {
                data.put("openid", userEntity.getWxOpenId());
            }
        }
        //使用官方API请求预付订单
        Map<String, String> response = wxpay.unifiedOrder(data);
        for (String key : response.keySet()) {
            log.info("微信支付订单微信返回参数：keys:" + key + "    value:" + response.get(key).toString());
        }
        if ("SUCCESS".equals(response.get("return_code"))) {//主要返回以下5个参数
            Map<String, String> param = new HashMap<>();
            if (classify == 1) {

                param.put("appid", config.getAppID());
                param.put("partnerid", response.get("mch_id"));
                param.put("prepayid", response.get("prepay_id"));
                param.put("package", "Sign=WXPay");
                param.put("noncestr", generateNonceStr);
                param.put("timestamp", currentTimeMillis);
                param.put("sign", WXPayUtil.generateSignature(param, config.getKey(),
                        WXPayConstants.SignType.MD5));
                param.put("outtradeno", outTradeNo);
            }else if(classify==2 || classify==3) {
                param.put("appid", config.getAppID());
                param.put("partnerid", response.get("mch_id"));
                param.put("prepayid", response.get("prepay_id"));
                param.put("noncestr", generateNonceStr);
                param.put("timestamp", currentTimeMillis);
                    /*param.put("sign", WXPayUtil.generateSignature(param, config.getKey(),
                            WXPayConstants.SignType.MD5));*/
                String stringSignTemp = "appId=" + config.getAppID() + "&nonceStr=" + generateNonceStr + "&package=prepay_id=" + response.get("prepay_id") + "&signType=MD5&timeStamp=" + currentTimeMillis + "" + "&key=" + config.getKey();
                String sign = MD5Util.md5Encrypt32Upper(stringSignTemp).toUpperCase();
                param.put("sign", sign);
                param.put("outtradeno", outTradeNo);
                param.put("package", "prepay_id=" + response.get("prepay_id"));//给前端返回的值
                param.put("mweb_url", response.get("mweb_url"));
                param.put("trade_type", response.get("trade_type"));
                param.put("return_msg", response.get("return_msg"));
                param.put("result_code", response.get("result_code"));
                param.put("signType", "MD5");
            }else if(classify==4){
                param.put("mweb_url", response.get("mweb_url"));
            }else{
                param.put("code_url", response.get("code_url"));
            }
            return Result.success().put("data", param);
        }
        return Result.error("获取订单失败");
    }

    @Override
    public String payBack(String resXml, Integer type) {
        WXConfig config = null;
        try {
            config = new WXConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.error("进入回调了！！！");
        if (type == 1) {
            config.setAppId(commonInfoService.findOne(74).getValue());
        } else if (type == 2) {
            config.setAppId(commonInfoService.findOne(5).getValue());
        } else {
            config.setAppId(commonInfoService.findOne(45).getValue());
        }
        config.setKey(commonInfoService.findOne(75).getValue());
        config.setMchId(commonInfoService.findOne(76).getValue());
        WXPay wxpay = new WXPay(config);
        String xmlBack = "";
        Map<String, String> notifyMap = null;
        try {
            notifyMap = WXPayUtil.xmlToMap(resXml);         // 调用官方SDK转换成map类型数据
            if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {//验证签名是否有效，有效则进一步处理
                log.error("验证成功！！！");
                String return_code = notifyMap.get("return_code");//状态
                String out_trade_no = notifyMap.get("out_trade_no");//商户订单号
                if (return_code.equals("SUCCESS")) {
                    log.error("验证成功222！！！");
                    if (out_trade_no != null) {
                        // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户的订单状态从退款改成支付成功
                        // 注意特殊情况：微信服务端同样的通知可能会多次发送给商户系统，所以数据持久化之前需要检查是否已经处理过了，处理了直接返回成功标志
                        //业务数据持久化
                        log.error("订单号！！！" + out_trade_no);

                        // 新建线程池来处理消息推送
                        ExecutorService exec = Executors.newFixedThreadPool(5);

                        Runnable runnable = new Runnable() {
                            @Override
                            public void run() {
                                // 根据订单编号获取订单（helpOrder）
                                HelpOrder helpOrder1 = helpOrderDao.selectOne(new LambdaQueryWrapper<HelpOrder>().eq(HelpOrder::getOrderNo, out_trade_no));
                                if(ObjectUtils.isEmpty(helpOrder1)){
                                    // 向附近的商家和师傅推送这个订单
                                    // 1.获取这个订单的经纬度
                                    String latitude = helpOrder1.getLatitude();//纬度
                                    String longitude = helpOrder1.getLongitude();//经度
                                    // 2.获取到系统配置的推送范围
                                    Integer pushRange = Integer.parseInt(commonInfoService.findOne(628).getValue());
                                    // 3.获取到所有的师傅和商家
                                    List<UserEntity> masterAndShop = userDao.getMasterAndShop();
                                    // 4.过滤掉距离大于推送范围的师傅和商家
                                    List<UserEntity> filterList = masterAndShop.stream().filter(item -> {
                                        GlobalCoordinates target = new GlobalCoordinates(Double.parseDouble(latitude), Double.parseDouble(longitude));
                                        GlobalCoordinates source = new GlobalCoordinates(Double.parseDouble(item.getLatitude()), Double.parseDouble(item.getLongitude()));
                                        Integer distance = (int) LonLatUtil.getDistanceMeter(target, source, Ellipsoid.Sphere);//计算两个经纬度之间的距离
                                        return distance <= pushRange * 1000;
                                    }).collect(Collectors.toList());
                                    // 5.向师傅和商家推送站内消息、微信服务消息、App消息
                                    for(UserEntity userEntity : filterList){
                                        // 5.1 先判断是师傅还是商家
                                        if(userEntity.getUserType() == 3 && (userEntity.getIsAuthentication() == 1 || userEntity.getIsAuthentication() == 3)){
                                            // 5.2 向师傅推送站内消息、微信服务消息、App消息
                                            // 5.2.1 推送站内消息
                                            MessageInfo messageInfo = new MessageInfo();
                                            messageInfo.setTitle("订单提醒");
                                            messageInfo.setState(String.valueOf(7));
                                            messageInfo.setContent("有用户下单了,请及时接单");
                                            messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                                            messageInfo.setUserName(userEntity.getUserName());
                                            messageInfo.setIsSee("0");
                                            messageService.saveBody(messageInfo);

                                            // 5.2.2 推送微信服务消息
                                            List<String> msgList = new ArrayList<>();
                                            String masterValue = commonInfoService.findOne(630).getValue(); // 模板id
                                            msgList.add(helpOrder1.getOrderNo());
                                            msgList.add(fixedClassifyService.getById(helpOrder1.getFixedClassifyId()).getClassifyName());
                                            msgList.add("1");
                                            msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                                            msgList.add(userService.getById(helpOrder1.getUserId()).getUserName());
                                            SenInfoCheckUtil.sendMasterMsg(userEntity.getMasterOpenId(),masterValue,msgList,1);

                                        }
                                        if(userEntity.getUserType() == 2 && userEntity.getIsAuthentication() == 2){
                                            // 5.3 向商家推送站内消息、微信服务消息、App消息
                                            // 5.3.1 推送站内消息
                                            MessageInfo messageInfo = new MessageInfo();
                                            messageInfo.setTitle("订单提醒");
                                            messageInfo.setState(String.valueOf(8));
                                            messageInfo.setContent("有用户下单了,请及时接单");
                                            messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                                            messageInfo.setUserName(userEntity.getUserName());
                                            messageInfo.setIsSee("0");
                                            messageService.saveBody(messageInfo);

                                            // 5.3.2 推送微信服务消息
                                            List<String> msgList = new ArrayList<>();
                                            String masterValue = commonInfoService.findOne(235).getValue(); // 模板id
                                            msgList.add(helpOrder1.getOrderNo());
                                            msgList.add(fixedClassifyService.getById(helpOrder1.getFixedClassifyId()).getClassifyName());
                                            msgList.add("1");
                                            msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                                            msgList.add(userService.getById(helpOrder1.getUserId()).getUserName());
                                            SenInfoCheckUtil.sendShopMsg(userEntity.getShopOpenId(),masterValue,null,msgList,1);
                                        }
                                    }
                                }
                            }
                        };
                        exec.execute(runnable);




                        PayDetails payDetails = payDetailsDao.selectByOrderId(out_trade_no);
                        if (payDetails.getState() == 0) {
                            payDetailsDao.updateState(payDetails.getId(), 1, sdf.format(new Date()), "");
                            if (payDetails.getType() == 1) {
                                //设置查询条件
                                QueryWrapper<PayOrder> queryWrapper = new QueryWrapper<>();
                                //根据订单编号去查询订单
                                queryWrapper.eq("orders_no", out_trade_no);
                                //去订单表中查询到该订单
                                PayOrder orders = payOrderDao.selectOne(queryWrapper);


                                //改变订单状态
                                orders.setState(1);
                                orders.setPayWay(type);
                                //设置订单更新时间
                                orders.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                payOrderDao.updateById(orders);
                                //调用处理接口
                                userMoneyDao.updateMayMoney(1, orders.getUserId(), orders.getMoney());
                                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                                userMoneyDetails.setUserId(orders.getUserId());
                                userMoneyDetails.setTitle("微信充值");
                                userMoneyDetails.setContent("微信充值:" + orders.getPayMoney());
                                userMoneyDetails.setType(1);
                                userMoneyDetails.setMoney(orders.getMoney());
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                userMoneyDetails.setCreateTime(sdf.format(new Date()));
                                userMoneyDetailsService.save(userMoneyDetails);
                            } else if (payDetails.getType() == 2) {
                                Orders orders = ordersDao.selectOne(new QueryWrapper<Orders>().eq("orders_no", payDetails.getOrderId()));
                                UserEntity userEntity = userService.selectUserById(orders.getUserId());
                                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                                userMoneyDetails.setMoney(orders.getPayMoney());
                                userMoneyDetails.setUserId(orders.getUserId());
                                userMoneyDetails.setContent("微信支付订单：" + orders.getOrdersNo());
                                userMoneyDetails.setTitle("下单成功");
                                userMoneyDetails.setType(2);
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                                userMoneyDetailsService.save(userMoneyDetails);
                                MessageInfo messageInfo = new MessageInfo();
                                messageInfo.setContent("订单下单成功：" + orders.getOrdersNo());
                                messageInfo.setTitle("订单通知");
                                messageInfo.setState(String.valueOf(4));
                                messageInfo.setUserName(userEntity.getUserName());
                                messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                                messageInfo.setCreateAt(simpleDateFormat.format(new Date()));
                                messageInfo.setIsSee("0");
                                messageService.saveBody(messageInfo);
                                if (StringUtil.isNotBlank(userEntity.getClientid())) {
                                    userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid());
                                }
                                String userName = userEntity.getUserName();
                                orders.setState("4");
                                orders.setIsRemind(0);
                                orders.setPayWay(2);
                                ordersDao.updateById(orders);
                                OrderTaking byId = orderTakingService.getById(orders.getOrderTakingId());
                                userEntity = userService.selectUserById(byId.getUserId());
                                MessageInfo messageInfos = new MessageInfo();
                                messageInfos.setContent("订单接单成功：" + orders.getOrdersNo());
                                messageInfos.setTitle("订单通知");
                                messageInfos.setState(String.valueOf(6));
                                messageInfos.setUserName(userEntity.getUserName());
                                messageInfos.setUserId(String.valueOf(userEntity.getUserId()));
                                messageInfos.setCreateAt(simpleDateFormat.format(new Date()));
                                messageInfos.setIsSee("0");
                                messageService.saveBody(messageInfos);
                                if (StringUtil.isNotBlank(userEntity.getClientid())) {
                                    userService.pushToSingle(messageInfos.getTitle(), messageInfos.getContent(), userEntity.getClientid());
                                }


                                //小程序订阅号消息推送
                                CommonInfo shopTemplate = commonInfoService.findOne(235);
                                List<String> msgList = new ArrayList<>();
                                msgList.add(orders.getOrdersNo());//订单号
                                if (byId.getGameId().length() > 15) {
                                    byId.setGameId(byId.getGameId().substring(0, 15) + "...");
                                }
                                msgList.add(byId.getGameId());//商品名称
                                msgList.add(String.valueOf(orders.getOrderNumber()));//商品数量
                                msgList.add(orders.getCreateTime());//下单时间
                                msgList.add(userName);//客户名称
                                UserEntity shopEntity = userService.getById(orders.getOrderTakingUserId());
                                if (StringUtils.isNotEmpty(shopEntity.getShopOpenId())) {
                                    SenInfoCheckUtil.sendShopMsg(shopEntity.getShopOpenId(), shopTemplate.getValue(), null, msgList, 1);
                                }


                                messageInfo = new MessageInfo();
                                messageInfo.setTitle("订单通知");
                                messageInfo.setState(String.valueOf(10));
                                messageInfo.setIsSee("0");
                                messageService.saveBody(messageInfo);
                            } else if (payDetails.getType() == 4) {
                                ordersService.payBack(payDetails.getRelationId(), payDetails.getOrderType(), 1, BigDecimal.valueOf(payDetails.getMoney()),payDetails.getOrderId());
                                //缴纳保证金
                            } else if (payDetails.getType() == 5) {
                                userMoneyService.safetyMoneyCallback(payDetails);
                            } else if (payDetails.getType() == 6) {
                                Orders orders = ordersDao.selectOne(new QueryWrapper<Orders>().eq("orders_no",payDetails.getOrderId()));
                                userMoneyService.setMember(orders,payDetails.getUserId());
                            } else {
                                HelpOrder helpOrder = JSONObject.parseObject(payDetails.getRemark(), HelpOrder.class);
                                HelpOrder order = helpOrderDao.selectOne(new QueryWrapper<HelpOrder>().eq("order_no", payDetails.getOrderId()));
                                if (helpOrder.getTaskType() == 2) {
                                    HelpBidding bidding = biddingService.getById(payDetails.getRelationId());
                                    order.setPayWay(2);
                                    helpOrderService.choseUserOrder(bidding, order);
                                    System.err.println("微信手机支付回调成功订单号:" + out_trade_no + "");
                                    xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                                    return xmlBack;
                                }

                                UserEntity userEntity = userService.selectUserById(helpOrder.getUserId());
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                String date = sdf.format(new Date());
                                helpOrder.setStatus(1);
                                helpOrder.setCreateTime(date);
                                helpOrder.setMoney(helpOrder.getCommission());
                                CommonInfo one = commonInfoService.findOne(120);
                                String value = one.getValue();
                                Double mul = AmountCalUtils.mul(helpOrder.getCommission().doubleValue(), Double.parseDouble(value));
                                BigDecimal sub = AmountCalUtils.sub(helpOrder.getMoney(), BigDecimal.valueOf(mul));
                                helpOrder.setCommission(sub);
                                helpOrder.setPayWay(2);
                                helpOrder.setIsPay(1);
                                helpOrderDao.updateById(helpOrder);
                                if(helpOrder.getTaskType()==4){
                                    HelpTake helpTake=new HelpTake();
                                    helpTake.setOrderId(helpOrder.getId());
                                    helpTake.setUserId(helpOrder.getMasterUserId());
                                    helpTakeService.saveBody(helpTake);
                                }
                                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                                userMoneyDetails.setUserId(helpOrder.getUserId());
                                userMoneyDetails.setTitle("万能任务");
                                userMoneyDetails.setContent("万能任务微信支付扣款：" + helpOrder.getMoney());
                                userMoneyDetails.setType(2);
                                userMoneyDetails.setMoney(helpOrder.getMoney());
                                userMoneyDetails.setCreateTime(date);
                                userMoneyDetailsService.save(userMoneyDetails);
                                if (userEntity.getClientid() != null) {
                                    userService.pushToSingle("派发订单", "您的订单已经派发成功！", userEntity.getClientid());
                                }
                                MessageInfo messageInfo = new MessageInfo();
                                messageInfo.setContent("您的订单已经派发成功！");
                                messageInfo.setTitle("订单通知");
                                messageInfo.setState(String.valueOf(5));
                                messageInfo.setUserName(userEntity.getUserName());
                                messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                                messageService.saveBody(messageInfo);
                                messageInfo = new MessageInfo();
                                messageInfo.setTitle("订单通知");
                                messageInfo.setState(String.valueOf(11));
                                messageInfo.setIsSee("0");
                                messageService.saveBody(messageInfo);
                            }
                        }
                        log.error("微信手机支付回调成功订单号:" + out_trade_no + "");
                        xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                    } else {
                        log.error("微信手机支付回调成功订单号:" + out_trade_no + "");
                        xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                    }
                }
                return xmlBack;
            } else {
                // 签名错误，如果数据里没有sign字段，也认为是签名错误
                log.error("手机支付回调通知签名错误");
                xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                return xmlBack;
            }
        } catch (
                Exception e) {
            log.error("手机支付回调通知失败" + e.getMessage(),e);
            xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        return xmlBack;
    }


    public String getGeneralOrder() {
        Date date = new Date();
        String newString = String.format("%0" + 4 + "d", (int) ((Math.random() * 9 + 1) * 1000));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdf.format(date);
        return format + newString;
    }


    @Override
    public boolean refund(String ordersNo, BigDecimal money) {
        WXConfigUtil config = null;
        String h5Url = commonInfoService.findOne(19).getValue().split("://")[1];
        String filePath = "/www/wwwroot/"+h5Url+"/service/apiclient_cert.p12";
        try {
            config = new WXConfigUtil(filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int commInfoId = 0;
        PayDetails payDetails = payDetailsDao.selectByOrderId(ordersNo);
        Integer payWay = payDetails.getClassify();
        //orders.getPayWay(); //1app微信 2微信公众号 3微信小程序
        switch (payWay) {
            case 1:
                commInfoId = 74;
                break; //appId
            case 2:
                commInfoId = 5;
                break; //公众号id
            case 3:
                commInfoId = 45;
                break; //小程序id
        }
        config.setAppId(commonInfoService.findOne(commInfoId).getValue());
        config.setKey(commonInfoService.findOne(75).getValue());
        config.setMchId(commonInfoService.findOne(76).getValue());
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<>();
        data.put("appid", config.getAppID());
        data.put("mch_id", config.getMchID());
        data.put("nonce_str", WXPayUtil.generateNonceStr());
        try {
            data.put("sign", WXPayUtil.generateSignature(data, config.getKey(), WXPayConstants.SignType.MD5));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        data.put("out_trade_no", payDetails.getOrderId()); //订单号,支付单号一致
        data.put("out_refund_no", getGeneralOrder()); //退款单号，同一笔用不同的退款单号
        BigDecimal multiply = BigDecimal.valueOf(payDetails.getMoney()).multiply(BigDecimal.valueOf(100));
        BigDecimal refundMoney = money.multiply(BigDecimal.valueOf(100));

        String fee = String.valueOf(multiply.intValue());
        String refundMoneys = String.valueOf(refundMoney.intValue());
        data.put("total_fee", fee); //1块等于微信支付传入100);
        data.put("refund_fee", refundMoneys); //1块等于微信支付传入100);
        //使用官方API退款
        try {
            Map<String, String> response = wxpay.refund(data);
            for (String key : response.keySet()) {
                log.info("微信退款微信返回参数：keys:" + key + "    value:" + response.get(key).toString());
            }
            if ("SUCCESS".equals(response.get("return_code")) && "SUCCESS".equals(response.get("result_code"))) {//主要返回以下5个参数
                log.info("退款成功！"+payDetails.getOrderId());
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.info("微信退款异常：" + e.getMessage(), e);
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Result payMoneyRepairFee(Long userId, Long ordersId, BigDecimal money, Integer payType, Integer orderType, HttpServletRequest request) throws Exception {
        PayDetails payDetails = new PayDetails();
        payDetails.setState(0);
        payDetails.setCreateTime(sdf.format(new Date()));
        payDetails.setOrderId(getGeneralOrder());
        payDetails.setUserId(userId);
        payDetails.setMoney(money.doubleValue());
        payDetails.setClassify(payType);
        payDetails.setType(4);
        payDetails.setOrderType(orderType);
        payDetails.setRelationId(ordersId);
        payDetailsDao.insert(payDetails);
        return pay(payDetails.getMoney(), payType, userId, payDetails.getOrderId(), null,request);
    }

    @Override
    public Result wxPaySafetyMoney(Long userId, Integer classify, BigDecimal money, Integer type, HttpServletRequest request) throws Exception {
        CommonInfo safetyMoneyCommonInfo = commonInfoService.findOne(616);
        UserEntity userEntity = userService.selectUserById(userId);
        UserMoney userMoney = userMoneyDao.selectOne(new QueryWrapper<UserMoney>().eq("user_id", userEntity.getUserId()));
        BigDecimal safetyMoney = new BigDecimal(safetyMoneyCommonInfo.getValue());

        if (userMoney.getSafetyMoney().compareTo(safetyMoney) < 0) {
            String outTradeNo = getGeneralOrder();
            PayDetails payDetails = new PayDetails();
            payDetails.setState(0);
            payDetails.setCreateTime(sdf.format(new Date()));
            payDetails.setOrderId(outTradeNo);
            payDetails.setUserId(userId);
            payDetails.setMoney(money.doubleValue());
            payDetails.setClassify(classify);
            payDetails.setType(5);
            payDetailsDao.insert(payDetails);
            return pay(money.doubleValue(), classify, userId, outTradeNo, type,request);

        } else {
            return Result.error("你已缴纳足额保证金");
        }


    }
}